﻿// 导入必要的命名空间
using System;
using System.Diagnostics;
using System.Reflection;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Net; // 用于网络编程
using System.Threading; // 用于线程操作
using System.Configuration.Install;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace 安装服务测试
{
    public class Program : ServiceBase
    {
        private int port;
        private ManualResetEvent httpStarted;

        static void Main(string[] args)
        {
            if (args.Length > 0 && args[0].Equals("install", StringComparison.OrdinalIgnoreCase))
            {
                // 安装服务
                if (args.Length < 2)
                {
                    Console.WriteLine("请提供端口号");
                    return;
                }
                int port = int.Parse(args[1]);
                ServiceManager.InstallService(port);
            }
            else if (args.Length > 0 && args[0].Equals("uninstall", StringComparison.OrdinalIgnoreCase))
            {
                // 卸载服务
                if (args.Length < 2)
                {
                    Console.WriteLine("请提供端口号");
                    return;
                }
                int port = int.Parse(args[1]);
                ServiceManager.UninstallService(port);
            }
            else
            {
                // 作为服务运行
                ServiceBase.Run(new Program());
            }
        }

        public Program()
        {
            this.ServiceName = "MyHttpService";
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                // 解析命令行参数
                string[] commandLineArgs = Environment.GetCommandLineArgs();
                if (commandLineArgs.Length > 1)
                {
                    port = int.Parse(commandLineArgs[1]);
                }
                else
                {
                    port = 8080; // 默认端口
                }

                httpStarted = new ManualResetEvent(false);
                starthttp(port);
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry("MyHttpService", $"服务启动失败: {ex.Message}", EventLogEntryType.Error);
            }
        }

        protected override void OnStop()
        {
            // 停止服务逻辑
        }

        private static void starthttp(int port)
        {
            try
            {
                // 创建一个HttpListener实例，用于监听HTTP请求
                HttpListener listener = new HttpListener();
                // 设置监听的URL前缀，包括端口号
                listener.Prefixes.Add($"http://*:{port}/");
                // 启动监听器
                listener.Start();
                EventLog.WriteEntry("MyHttpService", $"HTTP 服务已启动，监听端口为：{port}", EventLogEntryType.Information);

                // 使用Task.Run启动一个异步任务，用于处理HTTP请求
                Task.Run(() =>
                {
                    while (true)
                    {
                        try
                        {
                            // 获取一个HTTP请求的上下文
                            HttpListenerContext context = listener.GetContext();
                            // 获取响应对象
                            HttpListenerResponse response = context.Response;
                            // 设置响应的内容类型和字符编码
                            response.ContentType = "text/html; charset=utf-8";
                            // 构建��应字符串，包含当前服务的端口号
                            string responseString = $"<html><body>当前服务的端口是：{port}</body></html>";
                            // 将响应字符串转换为字节数组
                            byte[] buffer = Encoding.UTF8.GetBytes(responseString);
                            // 设置响应的内容长度
                            response.ContentLength64 = buffer.Length;
                            // 使用using语句确保输出流被正确关闭
                            using (var output = response.OutputStream)
                            {
                                // 将响应数据写入输出流
                                output.Write(buffer, 0, buffer.Length);
                            }
                        }
                        catch (Exception ex)
                        {
                            EventLog.WriteEntry("MyHttpService", $"处理请求时出错: {ex.Message}", EventLogEntryType.Error);
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry("MyHttpService", $"启动HTTP监听器时出错: {ex.Message}", EventLogEntryType.Error);
            }
        }
    }

    [RunInstaller(true)]
    public class MyServiceInstaller : Installer
    {
        public MyServiceInstaller()
        {
            ServiceProcessInstaller processInstaller = new ServiceProcessInstaller();
            ServiceInstaller serviceInstaller = new ServiceInstaller();

            processInstaller.Account = ServiceAccount.LocalSystem;
            serviceInstaller.StartType = ServiceStartMode.Automatic;
            serviceInstaller.ServiceName = "MyHttpService";

            Installers.Add(processInstaller);
            Installers.Add(serviceInstaller);
        }
    }
}
